package com.qysoft.rapid.shiro;

import java.util.List;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.jfinal.plugin.ehcache.CacheKit;
import com.qysoft.dtkj.dtkj_gl.services.xtwh.RYGLService;
import com.qysoft.dtkj.dtkj_gl.services.xtwh.ZYGLService;
import com.qysoft.rapid.consts.RapidConsts;
import com.qysoft.rapid.domain.Bean;

/**
 * shiroRealm
 * @author liugong
 *
 */
public class RapidRealm extends AuthorizingRealm {

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		String rydm = (String) principals.fromRealm(getName()).iterator().next();
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		try {
			List<String> permissions = CacheKit.get("permissions", rydm);
			if (permissions == null) {
			permissions = ZYGLService.queryZyljByRydm(rydm);
				CacheKit.put("permissions", rydm, permissions);
			}
			info.addStringPermissions(permissions);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return info;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
		//通过用户名查找人员信息
		Bean ryxx;
		try {
			ryxx = RYGLService.queryRyByDm(usernamePasswordToken.getUsername());
		} catch (Exception e) {
			e.printStackTrace();
			throw new AuthenticationException("数据库连接失败！");
		}
		if (ryxx == null) {
			throw new UnknownAccountException("用户名或密码错误！");// 没找到帐号
		}
		String password = new Md5Hash(new String(usernamePasswordToken.getPassword()),RapidConsts.MD5_SALT).toString();
		if (!password.equals(ryxx.getStr("password"))) {
			throw new IncorrectCredentialsException("用户名或密码错误！"); //密码错误  
		}
		return new SimpleAuthenticationInfo(usernamePasswordToken.getUsername(), usernamePasswordToken.getPassword(),getName());
	}

}
